package cmich.cps.scheduler.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import cmich.cps.scheduler.SchedulingSystem;
import cmich.cps.scheduler.data.Course;

/**
 * The Class CourseController.
 * 
 * @author Jonathan Kissinger <kissi1j@cmich.edu>
 */
public class CourseController implements Controller {
	
	/** The table. */
	private final JTable table;
	
	/** The model. */
	private DefaultTableModel model;
	
	/** The system. */
	private SchedulingSystem system = SchedulingSystem.getInstance();
	
	/** The room combo box. */
	private JComboBox<String> roomComboBox = new JComboBox<String>();
	
	/** The room preference column. */
	private final int roomPreferenceColumn = 5;

	/**
	 * Instantiates a new course controller.
	 *
	 * @param table the table
	 */
	CourseController(JTable table) {
		this.table = table;
		String[] headers = { "Designator", "Number", "Section Number", "Has lab?", "Enrollment", "Room" };
		this.model = new DefaultTableModel(new Object[][] {}, headers ) {
			private static final long serialVersionUID = 1L;
			@Override  
			public Class<?> getColumnClass(int col) {  
				if(col == 3) {
					return Boolean.class;  
				}
				if(col == 4) {
					return Integer.class;
				}
				else {
					return String.class;  
				}
			}
		};
		this.table.setModel(this.model);
		this.table.setAutoCreateRowSorter(true);
		this.table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		this.table.getTableHeader().setReorderingAllowed(false);
		//Sets room preference to use combo box.
		TableColumn roomCol = table.getColumnModel().getColumn(roomPreferenceColumn);
		roomCol.setCellEditor(new ComboBoxEditor());
	}

	/* (non-Javadoc)
	 * @see cmich.cps.scheduler.gui.Controller#populate()
	 */
	public void populate() {
		model.setRowCount(0);
		for(Course c : system.getCourses()) {
			model.addRow(new Object[] { c.getDesignator(), c.getNumber(), c.getSectionNumber(), c.getHasLab(), c.getEnrollment().toString(), c.getRoomPreference()});
		}
		//Setup roomPreference comboBox
		roomComboBox.removeAllItems();
		roomComboBox.addItem("Any");
		for(int i=0;i<system.getRooms().size();i++) {
			roomComboBox.addItem(system.getRooms().get(i).getName());
		}
		table.setToolTipText(model.getRowCount() + " courses.");
	}

	/* (non-Javadoc)
	 * @see cmich.cps.scheduler.gui.Controller#addFunctionality()
	 */
	public void addFunctionality() {
		model.addTableModelListener(new TableModelListener() {
			@Override
			public void tableChanged(TableModelEvent e) {
				switch (e.getType()) {
				case TableModelEvent.INSERT:
					break;
				case TableModelEvent.UPDATE:
					int row = e.getFirstRow();
					int col = e.getColumn();
					Object object = model.getValueAt(row, col);
					//Fix to handle clicking on the combo box, but then not selecting an option
					if(col==roomPreferenceColumn && object==null) {
						String aValue = system.getCourses().get(row).getRoomPreference();
						model.setValueAt(aValue, row, roomPreferenceColumn);
						break;
					}
					if(!system.modifyCourse(row, col, object)) {
						populate();
					}
					break;
				case TableModelEvent.DELETE:
					break;
				}
			}
		});
		table.addMouseListener(new TableMenu());
		table.getParent().addMouseListener(new TableMenu());
	}

	/**
	 * @author Jonathan Kissinger <kissi1j@cmich.edu>
	 * 
	 * The Class TableMenu.
	 */
	private class TableMenu extends MouseAdapter {
		
		/* (non-Javadoc)
		 * @see java.awt.event.MouseAdapter#mouseReleased(java.awt.event.MouseEvent)
		 */
		@Override
		public void mouseReleased(MouseEvent e) {
			if (e.isPopupTrigger()) {
				JPopupMenu popup = new JPopupMenu();
				JMenuItem addItem = new JMenuItem("Add new course");
				addItem.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						if(system.addCourse()) {
							populate();
						}
					}
				});
				popup.add(addItem);
				int row = table.rowAtPoint(e.getPoint());
				if (row >= 0 && row < table.getRowCount()) {
					final int index = table.convertRowIndexToModel(row);
					final Course course = system.getCourses().get(index);
					JMenuItem copyItem = new JMenuItem("Copy " + course.getName() + " with new section number");
					copyItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent e) {
							if(system.copyCourse(course)) {
								populate();
							}
						}
					});
					popup.add(copyItem);
					JMenuItem deleteItem = new JMenuItem("Delete " + course.getName() + " (Section: " + course.getSectionNumber() + ")");
					deleteItem.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent e) {
							system.removeCourse(index);
							model.removeRow(index);
							table.setToolTipText(model.getRowCount() + " Courses.");
						}
					});
					popup.add(deleteItem);
					table.setRowSelectionInterval(row, row);
				} else {
					table.clearSelection();
				}
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		}
	}

	/**
	 * @author Jonathan Kissinger <kissi1j@cmich.edu>
	 * 
	 * The Class ComboBoxEditor.
	 */
	private class ComboBoxEditor extends DefaultCellEditor {
		
		/** The Constant serialVersionUID. */
		private static final long serialVersionUID = 10L;
		
		/**
		 * Instantiates a new combo box editor.
		 */
		public ComboBoxEditor() {
			super(roomComboBox);
		}
	}
}